# -*- coding: utf8 -*-

import os
import poppler
from gtk import gdk
from archive import BaseAdapter

class PDFArchive(BaseAdapter):

    def get_files( self ):

        names = []

        document = poppler.document_new_from_file("file://" + self.file_name, None)

        n_pages = document.get_n_pages()

        for i in range(n_pages):
            names.append("%s.jpg" % i)

        return names


    def _render_page(self, save_to_file, document, page_n, scale = 1.0, quality = 90):

        page = document.get_page( page_n )

        psize = page.get_size()

        pw = int( psize[0] )
        ph = int( psize[1] )

        pws = int( pw * scale )
        phs = int( ph * scale )

        if pws < 1:
            pws = 1
        if phs < 1:
            phs = 1

        buff = gdk.Pixbuf( gdk.COLORSPACE_RGB, False, 8, pws, phs )
        page.render_to_pixbuf( 0, 0, pws, phs, scale, 0, buff )

        del page

        buff.save( save_to_file, "jpeg", {"quality": "%d" % quality} )

        del buff

        return


    def extract_files( self, into_dir):
        document = poppler.document_new_from_file("file://" + self.file_name, None)
        n_pages = document.get_n_pages()
        for i in range(n_pages):
            page_path = os.path.join(into_dir, "%s.jpg" % i)
            self._render_page(page_path, document, i, 4.0)
        return
